// package_01/pages/cut-pic/index.js
function selectPhoto (callBack) {
  let itemList = [ '拍照', '从手机相册选择', '从聊天记录选择' ]
  wx.showActionSheet({
    itemList,
    success: (action) => {
      if (action.tapIndex === 0) {
        // 从拍照选择图片，使用 chooseMedia
        wx.chooseMedia({ sourceType: [ 'camera' ] })
      } else if (action.tapIndex === 1) {
        // 从手机相册选择图片，使用 chooseMedia
        wx.chooseMedia({ sourceType: [ 'album' ] })
      } else if (action.tapIndex === 2) {
        // 从聊天记录选择图片，使用 chooseMessageFile
        wx.chooseMessageFile({})
      }
    }
  })
}

let imgHeight = 300,
imgWidth = 300,
xScale = 1.0,
yScale = 1.0,
clipBoxMoveInnerX = 0,
clipBoxMoveInnerY = 0,
clipBoxBeforeScalePageX = 0,
clipBoxBeforeScalePageY = 0,
clipBoxBeforeScaleClipX = 0,
clipBoxBeforeScaleClipY = 0,
clipBoxBeforeScaleWidth = 0,
clipBoxBeforeScaleHeight = 0,
activeCorner = null,
preCtx = null,
drawImage = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagePath: '/assets/images/longpress-image-scan/wx-qr-code.jpg',
    clipX: 0,
    clipY: 0,
    clipImgX: 0,
    clipImgY: 0,
    croppingImageWidth: 0,
    croppingImageHeight: 0,
    imageWidth: 0, 
    imageHeight: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    

  },

  imgLoad(e){
    console.log(e);

    const { width, height } = e.detail
    imgHeight = height
    imgWidth = width 

    // 根据窗口大小和图片大小，设置图片显示尺寸以及缩放
    // imgHeight 和 imgWidth 表示当前图片的宽高
    const sys = wx.getSystemInfoSync()
    // 设置图片显示面板的宽高
    let panelW = sys.windowWidth - 20
    let panelH = sys.windowHeight - 100
    if (panelH / panelW >= imgHeight / imgWidth) {
      panelH = parseInt(panelW * imgHeight / imgWidth)
    } else {
      panelW = parseInt(panelH * imgWidth / imgHeight)
    }
    // 图片在宽高上的缩放比，用于裁剪图片时计算图片实际尺寸
    xScale = panelW / imgWidth
    yScale = panelH / imgHeight
    this.setData({
      // imagePath,
      // 图片显示面板宽高
      panelWidth: panelW,
      panelHeight: panelH,
      // 裁剪框的宽高，初始时与图片面板一样
      clipWidth: panelW,
      clipHeight: panelH,
      // 裁剪的实际宽高
      croppingImageWidth: imgWidth,
      croppingImageHeight: imgHeight,


      imageWidth: panelW,
      imageHeight: panelH
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const query = wx.createSelectorQuery()
    query.select('#main').fields({node: true, size: true}).exec(res => {
      console.log(res);
      const canvas = res[0].node
      preCtx = canvas.getContext('2d')
      drawImage = canvas.createImage()
      drawImage.src = this.data.imagePath
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  touchstartM (event) {
    const { clipX, clipY } = this.data
    const { pageX, pageY } = event.touches[0]
    // 获取鼠标点在裁剪框的内部位置信息
    clipBoxMoveInnerX = pageX - clipX
    clipBoxMoveInnerY = pageY - clipY
  },

  touchmoveM (event) {
    const { pageX, pageY } = event.touches[0]
    const { panelWidth, panelHeight, clipHeight, clipWidth } = this.data
  
    // 裁剪框不能脱离面板
    // X位置范围为 0 到 (面板宽度-裁剪框宽度)
    let clipX = pageX - clipBoxMoveInnerX
    clipX = Math.max(clipX, 0)
    const panelX = panelWidth - clipWidth
    clipX = Math.min(clipX, panelX)
    // Y位置范围为 0 到 (面板高度-裁剪框高度)
    let clipY = pageY - clipBoxMoveInnerY
    clipY = Math.max(clipY, 0)
    const panleY = panelHeight - clipHeight
    clipY = Math.min(clipY, panleY)
  
    // 裁剪框底图位置信息
    const clipImgX = 0 - clipX
    const clipImgY = 0 - clipY
  
    this.setData({
      clipX,
      clipY,
      clipImgX,
      clipImgY
    })
  },

  // 处理缩放动作中不同corner时的尺寸位置信息
  getClipX (clipWidth) {
    switch (activeCorner) {
      case 'leftTop':
      case 'leftBottom':
        return clipBoxBeforeScaleClipX + (clipBoxBeforeScaleWidth - clipWidth)
      case 'rightTop':
      case 'rightBottom':
        return clipBoxBeforeScaleClipX
      default:
        return 0
    }
  },
  getClipY (clipHeight) {
    switch (activeCorner) {
      case 'leftTop':
      case 'rightTop':
        return clipBoxBeforeScaleClipY + (clipBoxBeforeScaleHeight - clipHeight)
      case 'leftBottom':
      case 'rightBottom':
        return clipBoxBeforeScaleClipY
      default:
        return 0
    }
  },
  getScaleXWidthOffset (offsetW) {
    switch (activeCorner) {
      case 'leftTop':
      case 'leftBottom':
        return -offsetW
      case 'rightTop':
      case 'rightBottom':
        return offsetW
      default:
        return 0
    }
  },
  getScaleYHeightOffset (offsetH) {
    switch (activeCorner) {
      case 'rightBottom':
      case 'leftBottom':
        return offsetH
      case 'rightTop':
      case 'leftTop':
        return -offsetH
      default:
        return 0
    }
  },
  touchstart (event) {
    const dragId = event.currentTarget.dataset.id
    const { pageX, pageY } = event.touches[0]
    const { clipX, clipY, clipHeight, clipWidth } = this.data

    // 设置缩放时临时变量初始化值
    activeCorner = dragId
    clipBoxBeforeScalePageX = pageX
    clipBoxBeforeScalePageY = pageY
    clipBoxBeforeScaleClipX = clipX
    clipBoxBeforeScaleClipY = clipY
    clipBoxBeforeScaleWidth = clipWidth
    clipBoxBeforeScaleHeight = clipHeight
  },
  touchmove (event) {
    const { pageX, pageY } = event.touches[0]
    const { panelWidth, panelHeight } = this.data

    // 缩放在X上的偏移
    const xWidthOffset = this.getScaleXWidthOffset(pageX - clipBoxBeforeScalePageX)
    // 裁剪框最小宽度36
    let clipWidth = Math.max(clipBoxBeforeScaleWidth + xWidthOffset, 36)
    // 设置缩放最大宽度，放大时不能超过面板、缩小时不能超过初始裁剪框
    let tempPanelWidth = pageX > clipBoxBeforeScalePageX ? panelWidth - clipBoxBeforeScaleClipX : clipBoxBeforeScaleWidth + clipBoxBeforeScaleClipX
    // 设置裁剪框宽度
    clipWidth = Math.min(clipWidth, tempPanelWidth)

    // 缩放在Y上的偏移
    const yHeightOffset = this.getScaleYHeightOffset(pageY - clipBoxBeforeScalePageY)
    // 裁剪框最小高度36
    let clipHeight = Math.max(clipBoxBeforeScaleHeight + yHeightOffset, 36)
    // 设置缩放最大高度，放大时不能超过面板、缩小时不能超过初始裁剪框
    let tempPanelHeight = pageY > clipBoxBeforeScalePageY ? panelHeight - clipBoxBeforeScaleClipY : clipBoxBeforeScaleHeight + clipBoxBeforeScaleClipY
    // 设置裁剪框高度
    clipHeight = Math.min(clipHeight, tempPanelHeight)

    // 裁剪框位置信息
    let clipX = this.getClipX(clipWidth)
    let clipY = this.getClipY(clipHeight)
    // 裁剪框底图位置信息
    let clipImgX = 0 - clipX
    let clipImgY = 0 - clipY

    this.setData({
      clipWidth,
      clipHeight,
      clipX,
      clipY,
      clipImgX,
      clipImgY,
      croppingImageWidth: parseInt(clipWidth / xScale),
      croppingImageHeight: parseInt(clipHeight / yScale)
    })
  },


  cut(){
    wx.showLoading({ title: '正在裁剪...' })
    const { imageWidth, imageHeight, croppingImageWidth, croppingImageHeight, clipImgX, clipImgY } = this.data
    preCtx.clearRect(0, 0, imageWidth, imageHeight)
    const width = croppingImageWidth
    const height = croppingImageHeight
    const xPos = Math.abs(clipImgX / xScale)
    const yPos = Math.abs(clipImgY / yScale)
    console.log(drawImage, xPos, yPos, width, height, 0, 0, width, height);
    // 绘制裁剪区内的图片到画布上
    preCtx.drawImage(drawImage, xPos, yPos, width, height, 0, 0, width, height)
    
    preCtx.save()
    preCtx.restore()
    wx.hideLoading()
  },
  
  save(){
    const { croppingImageWidth, croppingImageHeight } = this.data
    const width = croppingImageWidth
    const height = croppingImageHeight
    preCtx.draw(false, function () {
      setTimeout(() => {
        // 将画布导出为临时图片文件
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width,
          height,
          destWidth: width,
          destHeight: height,
          canvasId: 'main',
          success: (canRes) => {
            wx.hideLoading()
            that.initImage(width, height, canRes.tempFilePath)
          },
          fail (err) {
            wx.hideLoading()
            console.log(err)
          }
        })
      }, 200)
    })
  }
  
})